<?php

/**
 * dyeOrderItem actions.
 *
 * @package    WacStorehouse
 * @subpackage dyeOrderItem
 * @author     JianBinBi <prince.bi@gmail.com>
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 *
 * notes:
 * if clone as another one, below tags need to be replace to ur target module tag
 * "dyeOrder", "DyeOrder", "dye_order"
 */
class dyeOrderItemActions extends WacCommonActions
{
     /**
     * get searching list
     * @package
     * @author     ben
     */
    public function executeGetList(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $jqGridDataHelper = JqGridDataHelper::getInstance();

        $arrParam = array();
        if($jqGridDataHelper->loadComplexQuery($request)) {

            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
                $arrParam['andWhere'] = array(
                        $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
                );
            }

            if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
                switch($request->getParameter(JqGridDataHelper::$KEY_SIDX)) {
                    case "dye_order_code":
                        $arrParam['orderBy'] = "wdo.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "jar_name":
                        $arrParam['orderBy'] = "wj.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "factory_name":
                        $arrParam['orderBy'] = "wf.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
//                    case "goods_category_name":
//                        $arrParam['orderBy'] = "wgc.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
//                        break;
                    case "goods_name":
                        $arrParam['orderBy'] = "wg.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "cotton_yarn_unit_consume":
                        $arrParam['orderBy'] = "wdoicc.cotton_yarn_unit_consume ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "cotton_yarn_expect_consume":
                        $arrParam['orderBy'] = "wdoicc.cotton_yarn_expect_consume ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "attrition_rate":
                        $arrParam['orderBy'] = "wdoicc.attrition_rate ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    default:
                        $arrParam['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                }
            }

            $resultSet = $this->mainModuleTable->getCustomList($arrParam, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }
        else {
            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD)=="parent_id") {
                $arrParam['andWhere'][] = "dye_order_id=".$this->getRequest()->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING);
            }
            $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false, $arrParam);
        }

        $filterResultSet = $this->filterList($resultSet);

        $pager = $this->mainModuleTable->getPager();
        $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

        return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
    }

    /*
   * override filter list
    */
    public function filterList($listObjs) {
        $filterArr = array();
        if(count($listObjs) > 0) {
            foreach($listObjs as $listObj) {
                $tmpArr = $listObj->toArray();
                $tmpArr['production_order_code']        = $listObj->getWacProductionOrder()->getCode();
                $tmpArr['dye_order_code']               = $listObj->getWacDyeOrder()->getCode();
                $tmpArr['goods_number_unit_code_name']  = $listObj->getWacGoodsNumberUnitCode()->getName();
                $tmpArr['factory_name']                 = $listObj->getWacFactory()->getName();
                $tmpArr['color_name']                   = $listObj->getWacColor()->getName();
                $tmpArr['jar_name']                     = $listObj->getWacJar()->getName();
                $tmpArr['axis_name']                    = $listObj->getWacAxis()->getName();
                $tmpArr['goods_category_name']          = $listObj->getWacGoodsCategory()->getName();
                $tmpArr['goods_name']                   = $listObj->getWacGoods()->getName();

                $cottonItemConsume = Doctrine::getTable(WacTable::$dyeOrderItemCottonConsume)->getListByItem($listObj)->getFirst();
                $tmpArr['cotton_goods_id']     = $cottonItemConsume->getGoodsId();
                $tmpArr['cotton_yarn_consume_amount']   = $cottonItemConsume->getCottonYarnConsumeAmount();
                $tmpArr['cotton_yarn_unit_consume']     = $cottonItemConsume->getCottonYarnUnitConsume();
                $tmpArr['cotton_yarn_expect_consume']   = $cottonItemConsume->getCottonYarnExpectConsume();
                $tmpArr['attrition_rate']               = $cottonItemConsume->getAttritionRate();

                $filterArr[] = $tmpArr;
            }
        }

        return $filterArr;
    }

    /*
   * @return inspect result
    */
    public function inspectDataValidation(sfWebRequest $request, $params=array()) {
        $result    = JsCommonData::getSuccessDatum();
        $reqParams = $request->getParameterHolder()->getAll();

//        if(empty($reqParams['goods_id']) || !Doctrine::getTable(WacTable::$goods)->isExistedId($reqParams['goods_id'])) {
//            $result = JsCommonData::getErrorDatum(
//                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_goods_category"),  WacErrorCode::$logicError
//            );
//            return $result;
//        }

        if(empty($reqParams['cotton_goods_id']) || !Doctrine::getTable(WacTable::$goods)->isExistedId($reqParams['cotton_goods_id'])) {
            $result = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_cotton_goods_category"),  WacErrorCode::$logicError
            );
            return $result;
        }

        if(isset($reqParams['cotton_goods_id'])) {
            $objGoods = Doctrine::getTable(WacTable::$goods)->findOneBy('id', $reqParams['cotton_goods_id']);
            $objDyeOrder = Doctrine::getTable(WacTable::$dyeOrder)->findOneBy('id', $reqParams['dye_order_id']);
            $theStrockGoods = $objDyeOrder->getWacSupplier()->getAppointedStockGoods($objGoods);
            if($reqParams['cotton_yarn_consume_amount'] > $theStrockGoods->getGoodsNumber())
            {
                $errorMsgPtn = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_goods_number_insufficient_in_factory");
                $options = array(
                    "exist_number"=>$theStrockGoods->getGoodsNumber(),
                    "consume_number"=>$reqParams['cotton_yarn_consume_amount']
                );
                $errorMsg = MessageHelper::getInstance()->getMsgOfInsufficientGoods($objGoods, $options, $errorMsgPtn);
                $result = JsCommonData::getErrorDatum(
                        $errorMsg,  WacErrorCode::$logicError
                );
                return $result;
            }
        }

        if(empty($reqParams['dye_order_id']) || !Doctrine::getTable(WacTable::$dyeOrder)->isExistedId($reqParams['dye_order_id'])) {
            $result = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_dye_order"),  WacErrorCode::$logicError
            );
            return $result;
        }

//        if(empty($reqParams['color_id']) || !Doctrine::getTable(WacTable::$color)->isExistedId($reqParams['color_id'])) {
//            $result = JsCommonData::getErrorDatum(
//                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_color"),  WacErrorCode::$logicError
//            );
//            return $result;
//        }
//
//        if(empty($reqParams['jar_id']) || !Doctrine::getTable(WacTable::$jar)->isExistedId($reqParams['jar_id'])) {
//            $result = JsCommonData::getErrorDatum(
//                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_jar"),  WacErrorCode::$logicError
//            );
//            return $result;
//        }

        if(empty($reqParams['axis_id']) || !Doctrine::getTable(WacTable::$axis)->isExistedId($reqParams['axis_id'])) {
            $result = JsCommonData::getErrorDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_axis"),  WacErrorCode::$logicError
            );
            return $result;
        }

//        if(empty($reqParams['factory_id']) || !Doctrine::getTable(WacTable::$factory)->isExistedId($reqParams['factory_id'])) {
//            $result = JsCommonData::getErrorDatum(
//                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_factory"),  WacErrorCode::$logicError
//            );
//            return $result;
//        }

        return $result;
    }

    /*
   * @return list data array
    */
    public function executeAdd(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
        $resultSet     = JsCommonData::getCommonDatum();
        $inspectResult = $this->inspectDataValidation($request);

        if($inspectResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $inspectResult;
        }
        else {
            $objDyeOrder = Doctrine::getTable(WacTable::$dyeOrder)->findOneBy('id', $reqParams['dye_order_id']);
            $targetItem  = $this->mainModuleTable->create();

            if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);

                $targetItem->setProductionOrderId($objDyeOrder->getProductionOrderId());
                $targetItem->setSrcProductionOrderId($objDyeOrder->getProductionOrderId());
                $targetItem->setDyeOrderId($objDyeOrder->getId());
                $targetItem->setSupplierId($objDyeOrder->getSupplierId());
                $targetItem->setFactoryId($objDyeOrder->getFactoryId());

                if(isset($reqParams['goods_id']) && isset($reqParams['goods_name'])) {
                    $tmpParams = array(
                          "id" => $reqParams['goods_id'],
                          "name" => $reqParams['goods_name'],
                          "jar_id" => $reqParams['jar_id'],
                          "jar_name" => $reqParams['jar_name'],
                          "color_id" => $reqParams['color_id'],
                          "color_name" => $reqParams['color_name'],
                          "axis_id" => $reqParams['axis_id'],
                          "wheelbase" => $reqParams['wheelbase'],
                        ) ;
                    $objGoods = Doctrine::getTable(WacTable::$goods)->register($tmpParams, $objDyeOrder);
                    $targetItem->setGoodsId($objGoods->getId());
                    $targetItem->setGoodsCategoryId($objGoods->getGoodsCategoryId());
                }
//                if(isset($reqParams['batch'])) {
//                    $targetItem->setBatch($reqParams['batch']);
//                }
                if(isset($reqParams["jar_id"]) && isset($reqParams["jar_name"])) {
                    $tmpParams = array(
                            'id' => $reqParams["jar_id"], 'name' => $reqParams["jar_name"],
                    );
                    $objJar = Doctrine::getTable(WacTable::$jar)->register($tmpParams);
                    $targetItem->setJarId($objJar->getId());
                }
                if(isset($reqParams["color_id"]) && isset($reqParams["color_name"])) {
                    $tmpParams = array(
                            'id' => $reqParams["color_id"], 'name' => $reqParams["color_name"],
                    );
                    $objColor = Doctrine::getTable(WacTable::$color)->register($tmpParams);
                    $targetItem->setColorId($objColor->getId());
                }
                if(isset($reqParams['goods_number'])) {
                    $targetItem->setGoodsNumber($reqParams['goods_number']);
                }
                if(isset($reqParams['goods_number_unit_code'])) {
                    $targetItem->setGoodsNumberUnitCode($reqParams['goods_number_unit_code']);
                }
                if(isset($reqParams['goods_number_unit_price'])) {
                    $targetItem->setGoodsNumberUnitPrice($reqParams['goods_number_unit_price']);
                    $targetItem->setCost($reqParams['goods_number_unit_price'] * $reqParams['goods_number']);
                    $targetItem->setCurrencyCode($objDyeOrder->getCurrencyCode());
                }
                if(isset($reqParams['axis_id'])) {
                    $targetItem->setAxisId($reqParams['axis_id']);
                }
                if(isset($reqParams['axis_time'])) {
                    $targetItem->setAxisTime($reqParams['axis_time']);
                }
                if(isset($reqParams['wheelbase'])) {
                    $targetItem->setWheelbase($reqParams['wheelbase']);
                }
                if(isset($reqParams['quota_amount'])) {
                    $targetItem->setQuotaAmount($reqParams['quota_amount']);
                }
                if(isset($reqParams['processing_fee'])) {
                    $targetItem->setProcessingFee($reqParams['processing_fee']);
                }

                if(isset($reqParams['memo'])) {
                    $targetItem->setMemo($reqParams['memo']);
                }

                $targetItem->save();

                // record contton consume
                $cottonItemConsume = Doctrine::getTable(WacTable::$dyeOrderItemCottonConsume)->create();
                $cottonItemConsume->setDyeOrderId($targetItem->getDyeOrderId());
                $cottonItemConsume->setItemId($targetItem->getId());
                $cottonItemConsume->setCottonYarnConsumeUnitCode(Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$conttonUnitCode));
                if(isset($reqParams['cotton_goods_id'])) {
                    $cottonGoods = Doctrine::getTable(WacTable::$goods)->findOneBy("id", $reqParams['cotton_goods_id']);
                    $cottonItemConsume->setGoodsId($cottonGoods->getId());
                    $cottonItemConsume->setGoodsCategoryId($cottonGoods->getGoodsCategoryId());
                }
                if(isset($reqParams['cotton_yarn_consume_amount'])) {
                    $cottonItemConsume->setCottonYarnConsumeAmount($reqParams['cotton_yarn_consume_amount']);
                }
                if(isset($reqParams['cotton_yarn_unit_consume'])) {
                    $cottonItemConsume->setCottonYarnUnitConsume($reqParams['cotton_yarn_unit_consume']);
                }
                if(isset($reqParams['cotton_yarn_expect_consume'])) {
                    $cottonItemConsume->setCottonYarnExpectConsume($reqParams['cotton_yarn_expect_consume']);
                }
                if(isset($reqParams['attrition_rate'])) {
                    $cottonItemConsume->setAttritionRate($reqParams['attrition_rate']);
                }

                $cottonItemConsume->save();

                $this->afterAdd($request, $targetItem);


            }

            $resultSet['items'][0] = $targetItem->toArray();
            $resultSet['info']     = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

    }

    /*
   * @return list data array
    */
    public function executeEdit(sfWebRequest $request) {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('id'));

        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
        $resultSet     = JsCommonData::getCommonDatum();
        $inspectResult = $this->inspectDataValidation($request);

        if($inspectResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $inspectResult;
        }
        else {
            $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));

            if(count($reqParams)>0) {
                if(isset($reqParams['goods_id']) && isset($reqParams['goods_name'])) {
                    $tmpParams = array(
                          "id" => $reqParams['goods_id'],
                          "name" => $reqParams['goods_name'],
                          "jar_id" => $reqParams['jar_id'],
                          "jar_name" => $reqParams['jar_name'],
                          "color_id" => $reqParams['color_id'],
                          "color_name" => $reqParams['color_name'],
                          "axis_id" => $reqParams['axis_id'],
                          "wheelbase" => $reqParams['wheelbase'],
                        ) ;
                    $objGoods = Doctrine::getTable(WacTable::$goods)->register($tmpParams, $targetItem->getWacDyeOrder());
                    $targetItem->setGoodsId($objGoods->getId());
                    $targetItem->setGoodsCategoryId($objGoods->getGoodsCategoryId());
                }
//                if(isset($reqParams['batch'])) {
//                    $targetItem->setBatch($reqParams['batch']);
//                }

                // handle jar
                if(isset($reqParams["jar_id"]) && isset($reqParams["jar_name"])) {
                    $tmpParams = array(
                            'id' => $reqParams["jar_id"], 'name' => $reqParams["jar_name"],
                    );
                    $objJar = Doctrine::getTable(WacTable::$jar)->register($tmpParams);
                    $targetItem->setJarId($objJar->getId());
                }
                if(isset($reqParams["color_id"]) && isset($reqParams["color_name"])) {
                    $tmpParams = array(
                            'id' => $reqParams["color_id"], 'name' => $reqParams["color_name"],
                    );
                    $objColor = Doctrine::getTable(WacTable::$color)->register($tmpParams);
                    $targetItem->setColorId($objColor->getId());
                }
                if(isset($reqParams['goods_number'])) {
                    $targetItem->setGoodsNumber($reqParams['goods_number']);
                }
                if(isset($reqParams['goods_number_unit_code'])) {
                    $targetItem->setGoodsNumberUnitCode($reqParams['goods_number_unit_code']);
                }
                if(isset($reqParams['goods_number_unit_price'])) {
                    $targetItem->setGoodsNumberUnitPrice($reqParams['goods_number_unit_price']);
                    $targetItem->setCost($reqParams['goods_number_unit_price'] * $reqParams['goods_number']);
                }                
                if(isset($reqParams['axis_id'])) {
                    $targetItem->setAxisId($reqParams['axis_id']);
                }
                if(isset($reqParams['axis_time'])) {
                    $targetItem->setAxisTime($reqParams['axis_time']);
                }
                if(isset($reqParams['wheelbase'])) {
                    $targetItem->setWheelbase($reqParams['wheelbase']);
                }
                if(isset($reqParams['quota_amount'])) {
                    $targetItem->setQuotaAmount($reqParams['quota_amount']);
                }
                if(isset($reqParams['processing_fee'])) {
                    $targetItem->setProcessingFee($reqParams['processing_fee']);
                }

                if(isset($reqParams['memo'])) {
                    $targetItem->setMemo($reqParams['memo']);
                }

                $targetItem->save();

                // record contton consume
                $cottonItemConsume = Doctrine::getTable(WacTable::$dyeOrderItemCottonConsume)->getListByItem($targetItem)->getFirst();                
                $cottonItemConsume->setDyeOrderId($targetItem->getDyeOrderId());
                $cottonItemConsume->setItemId($targetItem->getId());
                if(isset($reqParams['cotton_goods_id'])) {
                    $cottonItemConsume->setGoodsCategoryId($reqParams['cotton_goods_id']);
                }
                if(isset($reqParams['cotton_yarn_consume_amount'])) {
                    $cottonItemConsume->setCottonYarnConsumeAmount($reqParams['cotton_yarn_consume_amount']);
                }
                if(isset($reqParams['cotton_yarn_unit_consume'])) {
                    $cottonItemConsume->setCottonYarnUnitConsume($reqParams['cotton_yarn_unit_consume']);
                }
                if(isset($reqParams['cotton_yarn_expect_consume'])) {
                    $cottonItemConsume->setCottonYarnExpectConsume($reqParams['cotton_yarn_expect_consume']);
                }
                if(isset($reqParams['attrition_rate'])) {
                    $cottonItemConsume->setAttritionRate($reqParams['attrition_rate']);
                }

                $cottonItemConsume->save();

                $this->afterEdit($request, $targetItem);

            }

            $resultSet['items'][0] = $targetItem->toArray();
            $resultSet['info']     = JsCommonData::getSuccessDatum(
                    Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
            );
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

    }

    /*
     * @return list data array
     */
    public function executeGetFormData(sfWebRequest $request) {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('dye_order_id'));

        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = JsCommonData::getCommonDatum();
        $resultSet['info'] = JsCommonData::getSuccessDatum();
        
        $objDyeOrder = Doctrine::getTable(WacTable::$dyeOrder)->findOneBy('id', $request->getParameter('dye_order_id'));
        $objCottonGoodsCategory = Doctrine::getTable(WacTable::$goodsCategory)->findOneBy("code", WacGoodsCategory::$predefinedClassCodes["classCottonCode"]);
        $resultSet['items']['cotton_stock_goods'] = $objDyeOrder->getWacSupplier()->getStockGoodsIdNameHash("", array($objCottonGoodsCategory->getId()), "in", array("valueFormat"=>"detail"));
        
        $resultSet['items']['unit'] = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();
        $resultSet['items']['axis'] = Doctrine::getTable(WacTable::$axis)->getIdNameHash();
        $resultSet['items']['default']['goods_number_unit_code'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$conttonUnitCode);



        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

    }
}